import numpy as np
from collections import Counter

class KNN:
    def __init__(self, k=3):
        self.k = k

    def fit(self, X, y):
        """训练方法,KNN无需训练，只需存储数据"""
        self.X_train = np.array(X)
        self.y_train = np.array(y)

    def predict(self, X):
        """预测方法"""
        X = np.array(X)
        y_pred = [self._predict(x) for x in X]
        return np.array(y_pred)

    def _predict(self, x):
        """单个样本的预测"""
        # 计算欧式距离
        distances = np.sqrt(np.sum((self.X_train - x) ** 2, axis=1))
        # 获取最近的k个样本的索引
        k_indices = np.argpartition(distances, self.k)[:self.k]
        # 获取对应的标签
        k_nearest_labels = self.y_train[k_indices]
        # 投票决定最终类别
        most_common = Counter(k_nearest_labels).most_common(1)
        return most_common[0][0]
    
    def accuracy(self, y_true, y_pred):
        """计算准确率"""
        return np.sum(y_true == y_pred) / len(y_true)


import argparse
def go():
    # 示例数据（特征+标签）
    X_train = np.array([[1, 2], [1.5, 1.8], [5, 8], [8, 8], [1, 0.6], [9, 11]])
    y_train = np.array(['A', 'A', 'B', 'B', 'A', 'B'])

    # 创建模型
    knn = KNN(k=3)
    knn.fit(X_train, y_train)

    # 测试数据
    X_test = np.array([[3, 4], [5, 6], [0, 0]])
    y_test = np.array(['A', 'B', 'A'])

    # 预测
    predictions = knn.predict(X_test)
    print("Predictions:", predictions)

    # 评估
    acc = knn.accuracy(y_test, predictions)
    print("Accuracy:", acc)

def test():
    # 示例数据（特征+标签）
    X_train = np.array([[1, 2], [1.5, 1.8], [5, 8], [8, 8], [1, 0.6], [9, 11]])
    y_train = np.array(['A', 'A', 'B', 'B', 'A', 'B'])

    # 创建模型
    knn = KNN(k=3)
    knn.fit(X_train, y_train)

    # 测试数据
    X_test = np.array([[3, 4], [5, 6], [0, 0]])
    y_test = np.array(['A', 'B', 'A'])
    X_test=np.array([[6, 2]])
    predictions = knn.predict(X_test)
    print("Prediction:", predictions[0])

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--input", help="输入文件路径")
    args = parser.parse_args()
    print("输入文件:", args.input)
    """go()"""
    test()




if __name__ == "__main__":
    main()
